/***************************************************************************************************
  * @file:     xxx.c
  * @author:   guangjieMVP
  * @github:   https://github.com/guangjieMVP
  * @version:  v1.0.0
  * @date:     2020-xx-xx
  * @brief:               
*****************************************************************************************************/

#include "message_driver.h"
#include "stdio.h"

/**
  * @brief:        判斷環形隊列是否空
  * @param[in]:     None
  * @retval[out]:   None
  * @author:       AresXu
  * @version:      v1.0.0
*/
bool is_msg_buf_empty(msg_driver_t *msg_buf)
{
    if(msg_buf->in == msg_buf->out)
    {
        return TRUE;
    }
    return FALSE;
}

/**
  * @brief:         判斷環形隊列是否满
  * @param[in]:     None
  * @retval[out]:   None
  * @note:            
  * @author:       AresXu
  * @version:      v1.0.0
*/
bool is_msg_buf_full(msg_driver_t *msg_buf)
{
    if ( ( (msg_buf->in+1) % MSG_DRIVER_SIZE) == msg_buf->out)
    {
        return TRUE;
    }
	
    return FALSE;
}

bool publish_msg(msg_driver_t *msg_buf, msg_node_t *msg)
{
    if( is_msg_buf_full (msg_buf) == TRUE )
    {
        return FALSE;
    }

    msg_buf->buf[msg_buf->in] = msg;
//	printf("in = %d\r\n", msg_buf->in);
	msg->handler(NULL);
    msg_buf->in = (++msg_buf->in) % MSG_DRIVER_SIZE;    //防止越界
	
	return TRUE;
}


static msg_node_t *get_messge(msg_driver_t *msg_buf)
{
	msg_node_t *msg = NULL;
    if( is_msg_buf_empty(msg_buf) )
    {
        return NULL;
    }

    msg = msg_buf->buf[msg_buf->out];
//	printf("out = %d\r\n", msg_buf->out);
    msg_buf->out = (++msg_buf->out) % MSG_DRIVER_SIZE;    //防止越界

    return msg;
} 


//主函数循环调用
void message_driver_handle(msg_driver_t *msg_buf)
{
	msg_node_t *msg;
	while( (msg = get_messge(msg_buf)) != NULL )
	{
		if (msg->handler != NULL)
			msg->handler(msg->parm);
	}
}







